package com.kmzx.one.project.config.listener;

import com.kmzx.one.common.constants.Constants;
import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.entity.ProductSelf;
import com.kmzx.one.project.entity.UserOrder;
import com.kmzx.one.project.entity.UserPay;
import com.kmzx.one.project.entity.UserProfit;
import com.kmzx.one.project.entity.Warehouse;
import com.kmzx.one.project.entity.WarehouseDetail;
import com.kmzx.one.project.events.InvalidOrderEvent;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.ProductMapper;
import com.kmzx.one.project.mapper.ProductSelfMapper;
import com.kmzx.one.project.mapper.UserOrderMapper;
import com.kmzx.one.project.mapper.UserPayMapper;
import com.kmzx.one.project.mapper.UserProfitMapper;
import com.kmzx.one.project.mapper.UserRankMapper;
import com.kmzx.one.project.mapper.WarehouseMapper;
import com.kmzx.one.project.others.dso.ProductSelfJoinSKU;
import com.kmzx.one.project.others.dto.FreightInfo;
import com.kmzx.one.project.others.dto.UserProfitInfo;
import com.kmzx.one.project.others.dto.UserRankInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Project selections
 * @Author: sunii
 * @Date: 2019/12/28-17:56
 */


@Component("invalidOrderEventListener")
public class InvalidOrderEventListener {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private CustomerMapper customerMapper;

//    @Autowired
//    private OrderBillMoneyMapper orderBillMoneyMapper;

    @Autowired
    private UserPayMapper userPayMapper;

    @Autowired
    private UserProfitMapper userProfitMapper;

    @Autowired
    WarehouseMapper warehouseMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    private UserRankMapper userRankMapper;

    @Autowired
    ProductSelfMapper productSelfMapper;

    @Autowired
    private RedisTemplate<String, Object> stringObjectRedisTemplate;

    @Async
    @EventListener(classes = {InvalidOrderEvent.class})
    @Transactional(rollbackFor = Exception.class)
    public void defaultInvalidOrderEventListener(InvalidOrderEvent invalidOrderEvent) {
        String orderId = invalidOrderEvent.getOrderId();

        Date date = new Date();
        UserOrder userOrder = new UserOrder();
        userOrder.setId(orderId);
        userOrder.setUpdateTime(date);
        userOrder.setStates(5);

        // 更新主订单
        userOrderMapper.updateByIdSelective(userOrder);
        // 更新子订单
        userOrderMapper.batchUpdateSubOrder(orderId, 5, date);


        UserOrder order = userOrderMapper.selectById(orderId);
        UserRankInfo rankInfo = userRankMapper.selectUserRankTabs(order.getUserId());
        stringObjectRedisTemplate.delete(Constants.rank_up_prefix + ":" + order.getUserId() + ":" + rankInfo.getRankNum());


        BigDecimal repoMoney = order.getPayMoney();
        BigDecimal profitMoney = order.getProfitMoney();

        if (repoMoney != null && repoMoney.compareTo(BigDecimal.ZERO) > 0) {
            FreightInfo freight = customerMapper.selectUserFreight(order.getUserId());
            String tempId = freight.getTempId();
            UserPay userPay = new UserPay();
            userPay.setMoney(freight.getMoney().add(repoMoney));
            userPay.setUpdateTime(date);
            userPay.setId(tempId);
            userPayMapper.updateByIdSelective(userPay);

        }

        if (profitMoney != null && profitMoney.compareTo(BigDecimal.ZERO) > 0) {
            UserProfitInfo userProfitInfo = customerMapper.selectUserProfit(order.getUserId());
            UserProfit userProfit = new UserProfit();
            userProfit.setId(userProfitInfo.getTemps());
            userProfit.setUpdateTime(date);
            userProfit.setProfitMoney(userProfitInfo.getCanPay().add(profitMoney));
            userProfitMapper.updateByIdSelective(userProfit);
        }


        List<WarehouseDetail> warehouseDetails = warehouseMapper.selectWarehouseInfoByOrderId(orderId, 0);

        List<Warehouse> warehouseList = new ArrayList<>();
        if (warehouseDetails!=null && warehouseDetails.size()>0) {


            Map<String, List<WarehouseDetail>> collect = warehouseDetails.stream().collect(Collectors.groupingBy(WarehouseDetail::getAttributeWithCategoryId));

            for (Map.Entry<String, List<WarehouseDetail>> entry : collect.entrySet()) {
                List<WarehouseDetail> value = entry.getValue();
                value.sort(Comparator.comparing(WarehouseDetail::getWarehouseBatch).reversed());
/*

                String attributeWithCategoryId = value.get(0).getAttributeWithCategoryId();
                Warehouse wh = warehouseMapper.selectWarehouseBySkuId(attributeWithCategoryId);
                if(wh.getIsBack()==1){

                }else {

                }
*/

                for (int i = 0; i < value.size(); i++) {
                    WarehouseDetail warehouseDetail = value.get(i);
                    Integer order_down_number = warehouseDetail.getProductNumber();
                    warehouseDetail.setStates(1);
                    warehouseDetail.setUpdateTime(date);

                    Warehouse warehouse = warehouseMapper.selectWarehouseById(warehouseDetail.getWarehouseId());
                    if (warehouse != null) {
                        Integer isBack = warehouse.getIsBack();
                        if (isBack == 1) {
                            List<ProductSelf> selfList = productSelfMapper.selectByProdIdHas(warehouseDetail.getProductId());

                            for (ProductSelf self : selfList) {
                                ProductSelfJoinSKU selfJoinSKU = productSelfMapper.selectProductSelfJoinSKUOne(self.getProductSubsId());
                                Integer isMulti = self.getIsMulti();
                                if(isMulti==0){
                                    selfJoinSKU = productSelfMapper.selectProdSelfJoinSKUSingle(self.getSkuId());
                                }

                                selfJoinSKU.setNeedNum(self.getNeedNum());
                                List<Warehouse> whList = warehouseMapper.selectWarehouseByProdIdSKU(selfJoinSKU.getProductSubsId(), selfJoinSKU.getSkuId(),warehouse.getTradeNum());
                                for (int j = 0; j < whList.size(); j++) {
                                    Warehouse whl = whList.get(j);
                                    Integer nowNumber = whl.getNowNumber();
                                    Integer behalf = whl.getBehalf();
                                    Integer warehouseNumber = whl.getWarehouseNumber();
                                    int num = order_down_number * selfJoinSKU.getProdNum() * selfJoinSKU.getNeedNum();
                                    if (warehouseNumber == nowNumber) {
                                        continue;
                                    } else {
                                        if (warehouseNumber >= nowNumber + num) {
                                            if(behalf!=null&& behalf==0){
                                                whl.setNowNumber(0);
                                            }else {
                                                whl.setNowNumber(nowNumber + num);
                                            }
                                            whl.setUpdateTime(date);
                                            WarehouseDetail whd1 = new WarehouseDetail();
                                            whd1.setId(UUIDGenerator.generate())
                                                    .setCreateTime(date).setUpdateTime(date)
                                                    .setSubsCodes(warehouseDetail.getSubsCodes())
                                                    .setStates(6)
                                                    .setOrdersId(warehouseDetail.getOrdersId())
                                                    .setOrderCodes(warehouseDetail.getOrderCodes());
                                            whd1.setWarehouseBatch(whl.getWarehouseBatch())
                                                    .setProductMoney(null).setNowCost(whl.getNowCost())
                                                    .setProductNumber(num)
                                                    .setProductId(whl.getProductId())
                                                    .setProfiles(whl.getProfiles())
                                                    .setProductName(whl.getProductName())
                                                    .setAttributeWithCategoryId(whl.getAttributeWithCategoryId())
                                                    .setAttributeWithCategoryName(whl.getAttributeWithCategoryName());


                                            warehouseMapper.updateWarehouseByIdSel(whl);
                                            warehouseMapper.insertWarehouseDetail(whd1);
                                            break;
                                        } else {
                                            if(behalf!=null&& behalf==0){
                                                whl.setNowNumber(0);
                                            }else {
                                                whl.setNowNumber(warehouseNumber - nowNumber);
                                            }
                                            whl.setUpdateTime(date);
                                            WarehouseDetail whd1 = new WarehouseDetail();
                                            whd1.setId(UUIDGenerator.generate())
                                                    .setSubsCodes(warehouseDetail.getSubsCodes())
                                                    .setCreateTime(date).setUpdateTime(date)
                                                    .setStates(6)
                                                    .setOrdersId(warehouseDetail.getOrdersId())
                                                    .setOrderCodes(warehouseDetail.getOrderCodes());
                                            whd1.setWarehouseBatch(whl.getWarehouseBatch())
                                                    .setProductMoney(null).setNowCost(whl.getNowCost())
                                                    .setProductNumber(warehouseNumber - nowNumber)
                                                    .setProductId(whl.getProductId())
                                                    .setProfiles(whl.getProfiles())
                                                    .setProductName(whl.getProductName())
                                                    .setAttributeWithCategoryId(whl.getAttributeWithCategoryId())
                                                    .setAttributeWithCategoryName(whl.getAttributeWithCategoryName());


                                            warehouseMapper.updateWarehouseByIdSel(whl);
                                            warehouseMapper.insertWarehouseDetail(whd1);

                                            num = num - (warehouseNumber - nowNumber);
                                        }
                                    }
                                }
                            }
                        } else {
                            Integer behalf = warehouseDetail.getBehalf();
                            if (behalf != null && behalf == 0) {
                                warehouse.setNowNumber(0);
                            } else {
                                Integer old_number = warehouse.getNowNumber();
                                warehouse.setNowNumber(old_number + order_down_number);
                            }
                            warehouse.setUpdateTime(date);
                            warehouseList.add(warehouse);
                            // 将库存明细表回撤状态
                            warehouseMapper.batchUpdateWarehouseDetail(warehouseDetails);
                            // 将库存表回填
                            warehouseMapper.batchUpdateWarehouse(warehouseList);
                        }

                    }
                }
            }

//            for (WarehouseDetail warehouseDetail : warehouseDetails) {
//                // 取消了
//                Integer order_down_number = warehouseDetail.getProductNumber();
//                warehouseDetail.setStates(1);
//                warehouseDetail.setUpdateTime(date);
//                Warehouse warehouse = warehouseMapper.selectWarehouseByBatchSkuId(warehouseDetail.getAttributeWithCategoryId(), warehouseDetail.getWarehouseBatch());
//                if (warehouse != null) {
//                    Integer old_number = warehouse.getNowNumber();
//                    warehouse.setNowNumber(old_number + order_down_number);
//                    warehouse.setUpdateTime(date);
//                    warehouseList.add(warehouse);
//                }
//            }

        }

        logger.info("超时订单,失效,订单为:{}", userOrder);
    }


}
